package v1

import (
	"errors"
	"sync"
)

// 任务结构体
type task struct {
	cb   func(args ...interface{})
	args []interface{}
	next *task
}

// TaskChain 任务链表
type TaskChain struct {
	mu       sync.Mutex
	head     *task
	tail     *task
	count    int
	maxCount int
}

// NewTaskChain 创建新的任务链表
func NewTaskChain() *TaskChain {
	return &TaskChain{}
}

// Add 添加任务
func (tc *TaskChain) Add(cb func(args ...interface{}), args ...interface{}) error {

	tc.mu.Lock()
	defer tc.mu.Unlock()

	if tc.count+1 >= tc.maxCount {
		return errors.New("max count reached")
	}

	newTask := &task{cb: cb, args: args}

	if tc.tail == nil {
		tc.head = newTask
		tc.tail = newTask
	} else {
		tc.tail.next = newTask
		tc.tail = newTask
	}
	tc.count++
	return nil
}

// Next 获取下一个任务
func (tc *TaskChain) Next() *task {
	tc.mu.Lock()
	defer tc.mu.Unlock()

	if tc.head == nil {
		return nil
	}

	current := tc.head
	tc.head = current.next

	if tc.head == nil {
		tc.tail = nil
	}
	tc.count--

	return current
}

// IsEmpty 检查是否为空
func (tc *TaskChain) IsEmpty() bool {
	tc.mu.Lock()
	defer tc.mu.Unlock()
	return tc.count == 0
}

// Count 获取任务数量
func (tc *TaskChain) Count() int {
	tc.mu.Lock()
	defer tc.mu.Unlock()
	return tc.count
}
